package com.ling.pl.security.decision;

import com.ling.pl.security.model.DefaultPosition;
import com.ling.pl.security.model.DefaultUser;
import com.ling.pl.security.utils.AttributeType;
import com.ling.pl.security.utils.SecurityConfigAttribute;

import java.util.Collection;
import java.util.List;

/**
 * @author bo.wang
 */
public class PositionAccessDecisionVoter extends AbstractAccessDecisionVoter {

    @Override
    protected AttributeType getAttributeType() {
        return AttributeType.position;
    }

    @Override
    public int vote(DefaultUser authentication, Object object, Collection attributes) {
        List<DefaultPosition> loginUserPositions = authentication.getPositions();
        for (Object attribute : attributes) {
            SecurityConfigAttribute configAttribute = (SecurityConfigAttribute) attribute;
            if (!configAttribute.getAttributeType().equals(AttributeType.position)) {
                continue;
            }
            DefaultPosition position = (DefaultPosition) configAttribute.getMember();
            for (DefaultPosition userPosition : loginUserPositions) {
                if (position.getId().equals(userPosition.getId())) {
                    if (configAttribute.isGranted()) {
                        return ACCESS_GRANTED;
                    } else {
                        return ACCESS_DENIED;
                    }
                }
            }
        }
        return ACCESS_ABSTAIN;
    }
}
